<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Source extends BaseController {

	public function __construct() {
        parent::__construct();
        // 后台初始化方法
        $this->admin_init();
        // 用户类型判断
        if($this->userType != USER_TYPE_SCHOOL && $this->userType != USER_TYPE_TEACHER) redirect(admin_url("login"));
        // 加载类库
        $this->load->model('sourceModel');
        $this->load->model('schoolModel');
    }

    // 资源管理页面
	public function manage() {
        // 设置资源所有格式
        $this->formats = $this->_get_source_formats();
        // 设置资源所有状态
        $this->states = $this->_get_source_states();

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "source". DIRECTORY_SEPARATOR. "source_manage");
    }
    
    // 获取资源列表--资源管理页面
    public function get_source_list() {
        $format = $this->get('format');
        $state = $this->get('state');
        $title = trim($this->get('title'));
        // 设置分页参数
        $params['pageStart'] = $this->get('start');
        $params['pageSize']= $this->get("length");
        if($format){
            $params['format'] = $format;
        }
        if($state){
            $params['state'] = $state;
        }
        if($title){
            $params['title'] = $title;
        }
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['isDelete'] = 0;
        // 如果是教师登录，就只显示个人创建的资源
        if(USER_TYPE_TEACHER == $this->rmxUser['user_type']){
            $params['userId'] = $this->rmxUser['id'];
        }
        $sourceList = $this->sourceModel->get_source_list($params);
        foreach($sourceList as $key => $source){
            // 转换格式名
            $sourceList[$key]['format'] = transform_source_format($source['format']);
            // 获取创建用户名
            $teacher = $this->schoolModel->get_school_user_info_realname($source['user_id']);
            $sourceList[$key]['username'] = '';
            if($teacher){
                $sourceList[$key]['username'] = $teacher['realname'] ? $teacher['realname'] : $teacher['username'];
            }
            // 获取资源年级标题
            $grade = $this->sourceModel->get_source_grade_info($source['source_grade_id']);
            if($grade){
                $sourceList[$key]['grade_title'] = $grade['title'];
            }
            // 获取资源类型标题
            $type = $this->sourceModel->get_source_type_info($source['source_type_id']);
            if($type){
                $sourceList[$key]['type_title'] = $type['title'];
            }
            // 获取资源科目标题
            $subject = $this->sourceModel->get_source_subject_info($source['source_subject_id']);
            if($subject){
                $sourceList[$key]['subject_title'] = $subject['title'];
            }
            // 获取资源出版社标题
            $publisher = $this->sourceModel->get_source_publisher_info($source['source_publisher_id']);
            if($publisher){
                $sourceList[$key]['publisher_title'] = $publisher['title'];
            }
            // 转换资源审核状态
            $sourceList[$key]['state'] = transform_source_state($source['state']);
            // 转换是否资源共享
            $sourceList[$key]['is_shared'] = $source['is_shared'] ? '是' : '否';
        }

        $totalParams['getRowNumber'] = true;
        $totalParams['isDelete'] = 0;
        if($format){
            $totalParams['format'] = $format;
        }
        if($state){
            $totalParams['state'] = $state;
        }
        if($title){
            $totalParams['title'] = $title;
        }
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['isDelete'] = 0;
        $total = $this->sourceModel->get_source_list($totalParams);
        exit(admin_table_data($total, $sourceList));
    }

    // 上传资源页面
    public function upload_source() {
        // 生成又拍云签名
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);

        $params['isDelete'] = 0;
        // 按时间倒序
        $params['groupBy'] = 'createtime ASC';
        // 获取所有资源科目
        $this->subjects = $this->sourceModel->get_source_subject_list($params);
        // 获取所有资源类型
        $this->types = $this->sourceModel->get_source_type_list($params);
        // 获取所有资源出版社
        $this->publishers = $this->sourceModel->get_source_publisher_list($params);
        // 获取资源格式
        $this->format = $this->get('format');

        // 判断是新增还是更新
        $id = $this->get('id');
        $this->source = array();
        if(!empty($id)){
            $this->source = $this->sourceModel->get_source_info($id);
            // 更新的情况设置format为已建资源的格式
            $this->format = $this->source['format'];
            // 获取资源年级名称
            $grade = $this->sourceModel->get_source_grade_info($this->source['source_grade_id']);
            if(!empty($grade)){
                $this->source['grade_name'] = $grade['title'];
            }
            // var_export($this->source);exit;
            $link = json_decode($this->source['link'], true);
            if($link && $link['link']) {
                if(preg_match("/^.*\.(doc|docx|ppt|pptx|xls|xlsx)$/", $link['link'])) {
                    $this->source['linkPreview'] = 'https://view.officeapps.live.com/op/view.aspx?src=' . $link['link'];
                } else {
                    $this->source['linkPreview'] = $link['link'];
                }
            } else {
                $this->source['linkPreview'] = '';
            }
        }
        
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "source". DIRECTORY_SEPARATOR. "source_upload");
    }

    // 选择资源年级插件数据源
    public function select_source_grade_plugin_data_source() {
        // 全部资源年级
        $params['isDelete'] = 0;
        $gradeList = $this->sourceModel->get_source_grade_list($params);
        // 资源年级预定义
        $gradeArr = array();
        foreach($gradeList as $grade) {
            $gradeId = $grade['id'];
            $gradePid = $grade['grade_pid'];
            // 初始化数据
            $gradeTitle = $grade['title'];
            $tree['text'] = $gradeTitle;
            $tree['type'] = $gradePid ? 'item' : 'folder';
            $tree['attr'] = array("id" => $gradeId);

            // 父级学段
            if($gradePid == 0) {
                $grade['additionalParameters']['children'] = array();
                $gradeArr["label_". $gradeId] = $tree;
            } else {
                // 年级
                $gradeArr["label_". $gradePid]['additionalParameters']['children'][] = $tree;
            }
        }
        exit(json('', true, $gradeArr));
    }

    // 删除又拍云文件
    // public function delete_upyun_file() {
    //     $url = $this->post('url');
    //     // url去掉域名
    //     $url = str_replace(UP_URL, '', $url);
    //     // 加载又拍云sdk
    //     require_once('vendor/autoload.php');
    //     // 初始化又拍云接口
    //     $config = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
    //     $upyun = new Upyun\Upyun($config);
    //     // 不显示异常
    //     try{
    //         $upyun->delete($url);
    //     }catch(Exception $e){

    //     }
    //     exit(json('', true));
    // }

    // 保存资源
    public function save_source_action() {
        $format = $this->post('format');
        $sourceId = $this->post("id");
        $cover = $this->post('cover');
        $video = $this->post('video');
        $audio = $this->post('audio');
        $otherFormat = $this->post('other-format');
        $title = trim($this->post('title'));
        $gradeId = $this->post('grade');
        $typeId = $this->post('type');
        $subjectId = $this->post('subject');
        $publisherId = $this->post('publisher');
        $desc = trim($this->post("desc", false));
        $isShared = $this->post('is-shared');
        // 判空
        if(empty($format)){
            throw new Exception('资源格式不能为空');
        }
        if(empty($title)){
            throw new Exception('标题不能为空');
        }
        if(empty($gradeId)){
            throw new Exception('年级不能为空');
        }
        if(empty($typeId)){
            throw new Exception('类型不能为空');
        }
        if(empty($subjectId)){
            throw new Exception('科目不能为空');
        }
        if(empty($publisherId)){
            throw new Exception('出版社不能为空');
        }
        switch($format){
            // 如果是上传视频资源
            case SOURCE_FORMAT_VIDEO:
                if(empty($video)){
                    throw new Exception('视频不能为空');
                }
                // 视频字段先入库
                $data['link'] = $video;
                break;
            // 如果是上传音频资源
            case SOURCE_FORMAT_AUDIO:
                if(empty($audio)){
                    throw new Exception('音频不能为空');
                }
                // 音频字段先入库
                $data['link'] = $audio;
                break;
            // 如果是上传图文资源
            case SOURCE_FORMAT_IMAGE_TEXT:
                break;
            // 如果是上传其他资源
            case SOURCE_FORMAT_OTHER:
                if(empty($otherFormat)){
                    throw new Exception('文件不能为空');
                }
                // 其他资源字段先入库
                $data['link'] = $otherFormat;
                break;
        }
        // 入库
        $data['format'] = $format;
        $data['cover'] = $cover;
        $data['title'] = $title;
        $data['source_grade_id'] = $gradeId;
        $data['source_type_id'] = $typeId;
        $data['source_subject_id'] = $subjectId;
        $data['source_publisher_id'] = $publisherId;
        $data['desc'] = $desc;
        $data['is_shared'] = $isShared == 1 ? 1 : 0;
        $data['updatetime'] = date('Y-m-d H:i:s');
        // 如果是学校管理员，为审核通过状态，否则为未审核状态
        if(USER_TYPE_SCHOOL == $this->rmxUser['user_type']){
            $data['state'] = SOURCE_ACCEPTED;
        } else {
            $data['state'] = SOURCE_PENDING;
        }
        if(empty($sourceId)){
            // 新增资源
            $data['createtime'] = date('Y-m-d H:i:s');
            $data['user_id'] = $this->rmxUser['id'];
            $data['school_id'] = $this->rmxSchool['id'];
            $this->db->insert(SourceModel::$schoolSourceTable, $data);
        } else {
            // 修改资源
            $this->db->update(SourceModel::$schoolSourceTable, $data, "id={$sourceId}");
        }
        $msg = empty($sourceId) ? '新增资源成功' : '修改资源成功';
        exit(json($msg, true));
    }

    public function source_preview(){
        $this->sourceSrc = $this->get('source_src');
        // 判断是否是pdf格式
        if(strstr($this->sourceSrc, '.pdf')){
            $this->sourceFormat = 'pdf';
        } else {
            $this->sourceFormat = '';
        }
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "source". DIRECTORY_SEPARATOR. "source_preview");
    }

    // 删除资源
    public function source_delete_action() {
        $id = $this->post('id');
        $this->db->where('id', $id);
        $this->db->update(SourceModel::$schoolSourceTable, array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        ));
        exit(json('删除成功', true));
    }

    // 审核资源
    public function verify_source(){
        $id = $this->post('id');
        $action = $this->post('action');
        if($action === 'accept'){
            $state = SOURCE_ACCEPTED;
        } else {
            $state = SOURCE_REJECTED;
        }
        $this->db->where('id', $id);
        $this->db->update(SourceModel::$schoolSourceTable, array(
            'state' => $state,
            'updatetime' => date('Y-m-d H:i:s')
        ));
        exit(json('审核成功', true));
    }

    // 资源检索页面
	public function check() {
        // 设置所有资源格式
        $this->formats = $this->_get_source_formats();
        // 设置资源所有类型
        $this->states = $this->_get_source_states();
        // 设置资源所有科目
        $params['isDelete'] = 0;
        $this->subjects = $this->sourceModel->get_source_subject_list($params);
        // 设置资源所有出版社
        $this->publishers = $this->sourceModel->get_source_publisher_list($params);
        // 设置资源所有类型
        $this->types = $this->sourceModel->get_source_type_list($params);

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "source". DIRECTORY_SEPARATOR. "source_check");
    }

    // 获取资源列表--资源检索页面
    public function get_source_list_for_check() {
        $format = $this->get('format');
        $title = trim($this->get('title'));
        $subjectId = $this->get('subjectId');
        $publisherId = $this->get('publisherId');
        $typeId = $this->get('typeId');
        $gradeId = $this->get('gradeId');
        if($format){
            $params['format'] = $format;
        }
        if($title){
            $params['title'] = $title;
        }
        if($subjectId){
            $params['subjectId'] = $subjectId;
        }
        if($publisherId){
            $params['publisherId'] = $publisherId;
        }
        if($typeId){
            $params['typeId'] = $typeId;
        }
        if($gradeId){
            $params['gradeId'] = $gradeId;
        }
        // 设置分页参数
        $params['pageStart'] = $this->get('pageStart') ? $this->get('pageStart') : 0;
        $params['pageSize']= $this->get("pageSize") ? $this->get("pageSize") : 20;
        // 获取本校所有的资源，和其他学校共享的资源
        $params['sourceForCheck'] = array(
            'schoolId' => $this->rmxSchool['id'],
            'is_shared' => 1
        );
        // 只获取已通过审核的
        $params['state'] = SOURCE_ACCEPTED;
        $params['isDelete'] = 0;
        $sourceList = $this->sourceModel->get_source_list($params);

        foreach($sourceList as $key => $source){
            // 获取创建用户名
            $teacher = $this->schoolModel->get_school_user_info_realname($source['user_id']);
            $sourceList[$key]['username'] = $teacher['realname'] ? $teacher['realname'] : $teacher['username'];
            // 获取创建用户所在学校名
            $school = $this->schoolModel->get_school_info($sourceList[$key]['school_id']);
            $sourceList[$key]['school_name'] = $school['school_name'];
        }
        // echo '<pre>';var_dump($sourceList);exit;
        exit(json('', true, $sourceList));
    }

    // 资源详情页面
	public function detail() {
        $id = $this->get('id');
        // 获取资源详情
        $this->source = $this->sourceModel->get_source_info($id);
        // 获取创建用户名
        $teacher = $this->schoolModel->get_school_user_info_realname($this->source['user_id']);
        $this->source['username'] = $teacher['realname'] ? $teacher['realname'] : $teacher['username'];
        // 获取创建用户所在学校名
        $school = $this->schoolModel->get_school_info($this->source['school_id']);
        $this->source['school_name'] = $school['school_name'];

        $this->display(ADMIN_DIR . DIRECTORY_SEPARATOR . "source" . DIRECTORY_SEPARATOR . "source_detail");
    }

    // 获取资源所有格式
    private function _get_source_formats() {
        return  array(
            array(
                'value' => SOURCE_FORMAT_VIDEO,
                'name' => transform_source_format(SOURCE_FORMAT_VIDEO)
            ),
            array(
                'value' => SOURCE_FORMAT_AUDIO,
                'name' => transform_source_format(SOURCE_FORMAT_AUDIO)
            ),
            array(
                'value' => SOURCE_FORMAT_IMAGE_TEXT,
                'name' => transform_source_format(SOURCE_FORMAT_IMAGE_TEXT)
            ),
            array(
                'value' => SOURCE_FORMAT_OTHER,
                'name' => transform_source_format(SOURCE_FORMAT_OTHER)
            )
        );
    }

    // 获取资源所有状态
    private function _get_source_states() {
        return array(
            array(
                'value' => SOURCE_PENDING,
                'name' => transform_source_state(SOURCE_PENDING)
            ),
            array(
                'value' => SOURCE_ACCEPTED,
                'name' => transform_source_state(SOURCE_ACCEPTED)
            ),
            array(
                'value' => SOURCE_REJECTED,
                'name' => transform_source_state(SOURCE_REJECTED)
            )            
        );
    }
}